//
//  QRCodeViewController.swift
//  swift_wobo
//
//  Created by yuxin on 2018/11/17.
//  Copyright © 2018 wuxiantianli. All rights reserved.
//

import UIKit
import AVFoundation

let YXScreenSize : CGSize = UIScreen.main.bounds.size
let bottomView_H : CGFloat = 49.0


class QRCodeViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        if !Platform.isSimulator {
            startScan()
        }
        
    }
    
    private func startScan() {
        if !session.canAddInput(deviceInput!) {
            return
        }
        if !session.canAddOutput(output) {
            return
        }
        
        session.addInput(deviceInput!)
        session.addOutput(output)
        
        //设置所以类型都可以解析
        output.metadataObjectTypes = output.availableMetadataObjectTypes
        
        output.setMetadataObjectsDelegate(self, queue: DispatchQueue.main)
        
        view.layer.insertSublayer(previewLayer, at: 0)
        
        session.startRunning()
        
    }
    
    //MARK: - 懒加载
    private lazy var scanView : QRCodeScanningView = {
        let scan = QRCodeScanningView()
        scan.center = CGPoint(x: YXScreenSize.width/2.0, y: YXScreenSize.height/2.0)
        return scan
    }()
    
    private lazy var bottomleftBtn : TitleBottomButton = {
        let leftBtn = creatBottomBtn(title: "二维码", norImgName: "qrcode_tabbar_icon_qrcode", selImgName: "qrcode_tabbar_icon_qrcode_highlighted")
        leftBtn.frame = CGRect(x: 0.0, y: 0.0, width: YXScreenSize.width/2.0, height: bottomView_H)
        leftBtn.addTarget(self, action: #selector(bottomLeftBtnClick(btn:)), for: .touchUpInside)
        return leftBtn
    }()
    
    private lazy var bottomRightBtn : TitleBottomButton = {
        let rightBtn = creatBottomBtn(title: "条形码", norImgName: "qrcode_tabbar_icon_barcode", selImgName: "qrcode_tabbar_icon_barcode_highlighted")
        rightBtn.frame = CGRect(x: YXScreenSize.width/2.0, y: 0.0, width: YXScreenSize.width/2.0, height: bottomView_H)
        rightBtn.addTarget(self, action: #selector(bottomRightBtnClick(btn:)), for: .touchUpInside)
        
        return rightBtn
    }()
    
    private lazy var session : AVCaptureSession = AVCaptureSession()
    
    private lazy var deviceInput : AVCaptureDeviceInput? = {
        let device = AVCaptureDevice.default(for: AVMediaType.video)
        do{
            let input = try AVCaptureDeviceInput(device: device!)
            return input
        }catch {
            print(error)
            return nil
        }
    }()
    
    private lazy var output : AVCaptureMetadataOutput = AVCaptureMetadataOutput()
    
    private lazy var previewLayer: AVCaptureVideoPreviewLayer = {
        let layer = AVCaptureVideoPreviewLayer(session: session)
        layer.frame = UIScreen.main.bounds
        return layer
    }()
    

}

// MARK: - setupUI
extension QRCodeViewController {
    
    private func setupUI() {
        view.backgroundColor = UIColor.clear
        setupNaviView()
        setupBottomView()
        
        view.addSubview(scanView)
    }
    
    private func setupNaviView() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem.creatBarButtonItem(title: "关闭", target: self, action: #selector(naviLeftBtnClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem.creatBarButtonItem(title: "相册", target: self, action: #selector(naviRightBtnClick))
        UINavigationBar.appearance().tintColor = UIColor.orange
   }
    
    private func setupBottomView() {
        let bottomToolsView = UIView(frame: CGRect(x: 0, y: YXScreenSize.height-bottomView_H, width: YXScreenSize.width, height: bottomView_H))
        bottomToolsView.backgroundColor = UIColor.black
        
        bottomToolsView.addSubview(bottomleftBtn)
        bottomToolsView.addSubview(bottomRightBtn)
       
        view.addSubview(bottomToolsView)
        
        bottomLeftBtnClick(btn: bottomleftBtn)
    }
    
    private func creatBottomBtn(title: String, norImgName: String, selImgName: String) -> TitleBottomButton {
        let btn = TitleBottomButton(type: .custom)
        btn.setImage(UIImage(named: norImgName), for: .normal)
        btn.setImage(UIImage(named: selImgName), for: .selected)
        btn.setTitle(title, for: .normal)
        btn.setTitleColor(UIColor.white, for: .normal)
        btn.setTitleColor(UIColor.orange, for: .selected)
        return btn
    }

}

// MARK: - action
extension QRCodeViewController {
    @objc private func naviLeftBtnClick() {
        dismiss(animated: true, completion: nil)
    }
    @objc private func naviRightBtnClick() {
        print(#function)
    }
    @objc private func bottomLeftBtnClick(btn: UIButton) {
        bottomleftBtn.isSelected = true
        bottomRightBtn.isSelected = false
        scanView.scanViewType = ScanningViewType.QR
    }
    @objc private func bottomRightBtnClick(btn: UIButton) {
        bottomleftBtn.isSelected = false
        bottomRightBtn.isSelected = true
        scanView.scanViewType = ScanningViewType.BAR
    }
    
    
}

extension QRCodeViewController : AVCaptureMetadataOutputObjectsDelegate {
    func metadataOutput(_ output: AVCaptureMetadataOutput, didOutput metadataObjects: [AVMetadataObject], from connection: AVCaptureConnection) {
        for obj in metadataObjects {
            if obj is AVMetadataObject {
                print(obj)
                let codeObj = previewLayer.transformedMetadataObject(for: obj)
                print(codeObj as Any)
                
            }
        }
    }
}
